﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GestionePolveri2.DAL;
using GestionePolveriLib.BL;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data;
using GestionePolveriLib.Facades;
using System.Threading;

namespace GestionePolveriLib.Cache
{
    public partial class LookUpData
    {
        public event EventHandler DataLoaded;

        private GestionePolveriEntities m_context = null;
        private Dictionary<string, object> m_cache = null;
        private bool m_cacheLoaded = false;

        public bool CacheLoaded
        {
            get { return m_cacheLoaded; }
            set { m_cacheLoaded = value; }
        }

        public LookUpData()
        {
            m_cache = new Dictionary<string, object>();
            m_context = new GestionePolveriEntities();
        }

        public void LoadLookUps()
        {
            InitializeCache();
        }

        public void SetData(string key, object value)
        {
            if ((m_cache != null) && (m_cache.Count > 0))
            {
                m_cache.Add(key, value);
            }
        }

        public object GetData(string key)
        {
            object retValue = null;
            
            if ((m_cache != null) && (m_cache.Count > 0))
            {
                retValue = m_cache[key];
            }

            return retValue;
        }

        public void InitializeCache()
        {
            ThreadPool.QueueUserWorkItem(LoadData);
        }

        private void LoadData(object state)
        {
            GestionePolveriEntities context = new GestionePolveriEntities();
            List<LookUp_FamiglieColori_ColoriAbbinati_Result> result = context.LookUp_FamiglieColori_ColoriAbbinati(null, null, null).ToList();

            if (m_cache != null)
                m_cache.Clear();

            m_cache.Add("LookupFamiglie", result);

            if (DataLoaded != null)
            {
                DataLoaded(this, EventArgs.Empty);
            }
        }

        public void Refresh()
        {
            m_cache.Clear();

            InitializeCache();
        }
    }
}
